/*
 * PagoscomerciosFijosFrame.java
 *
 * Created on 13 de abril de 2008, 11:44 AM
 */
package org.pagos.vehiculos;

import org.pagos.ver.ImpuestosAgregarFrame;
import org.mybeans.Sesion;
import org.mybeans.ComerciosBeans;
import org.mybeans.ContribuyentesBeans;
import org.mybeans.RegimenBeans;
import org.mybeans.RecibesBeans;
import org.mybeans.RecibesDetallesBeans;
import org.mybeans.RecibesNumeracionBeans;
import org.mybeans.RegimenVehiculosBeans;
import org.mybeans.VehiculosBeans;
import org.mybeans.VehiculosInscripcionBeans;
import org.mybeans.VehiculosTraspasoNumeracionBeans;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.text.Format;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import javax.swing.DefaultCellEditor;
import javax.swing.JLabel;
import javax.swing.JMenuItem;
import javax.swing.JOptionPane;
import javax.swing.JPopupMenu; 
import javax.swing.JSeparator;
import javax.swing.JTextField;
import javax.swing.SwingUtilities;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.TableColumn;
import net.sf.jasperreports.engine.JasperCompileManager;
import net.sf.jasperreports.engine.JasperFillManager;
import net.sf.jasperreports.engine.JasperPrint;
import net.sf.jasperreports.engine.JasperReport;
import net.sf.jasperreports.view.JasperViewer;
import org.gingresos.recibos.PrinterRecibos;
import org.jdesktop.swingx.autocomplete.*;
import org.vehiculos.fideicomiso.VehiculosFideicomisoFrame;

/**
 *
 * @author  avbravo
 */
public class PagosVehiculosLiberarFideicomisoFrame extends javax.swing.JFrame {

    boolean focoVehiculo = false;
    boolean focoImpuesto = false;
    String reportSource;
    String reportDest;
    JTextField fieldPago;
    JTextField fieldSaldo;
    JTextField fieldExoneracion;
    JPopupMenu popupMenu = new JPopupMenu("Menu");
    JMenuItem menuPagar = new JMenuItem("Pagar");
    JMenuItem menuExonerar = new JMenuItem("Exonerar");
    JSeparator separator0 = new javax.swing.JSeparator();
    JMenuItem menuCerrar = new JMenuItem("Cerrar");
    JMenuItem menuEliminar = new JMenuItem("Eliminar");
    Sesion sesion;
    ComerciosBeans comerciosBeans;
    ContribuyentesBeans contribuyentesBeans;
    RegimenBeans regimenBeans;
    VehiculosBeans vehiculosBeans;
    VehiculosInscripcionBeans vehiculosInscripcionBeans;
    VehiculosTraspasoNumeracionBeans vehiculosTraspasoNumeracionBeans;
    RegimenVehiculosBeans regimenVehiculosBeans;
    RecibesBeans recibesBeans;
    RecibesDetallesBeans recibesDetallesBeans;
    RecibesNumeracionBeans recibesNumeracionBeans;
    int fila = -1;
    DefaultTableModel modelo;
    private int AnioRecibo;
    private int NumeroMes;
    String IdVehiculo;
    String TipoId = "vehiculos";
    private String idRegimen;
    String sql;
    String rowIdRegimen;
    String rowRegimen;
    double rowDeuda;
    double rowPago;
    double rowSaldo;
    double rowExoneracion;
    String rowTipo;
    String rowDetalle;
    double rowValor;
    double rowMorosidad;
    String rowComentario;
    int rowCantidad;
    double Pago = 0;
    double Exoneracion = 0;
    double Valor = 0.0;
    double Saldo = 0.0;
    double SaldoAnterior = 0.0;
    int IdRecibo = 0;
    Double TotalPagado = 0.0;
    Double TotalExonerado = 0.0;
    String idExoneracion = "";
    Double Deuda;
    boolean TieneExoneracion = false;
    boolean TieneAlgunRegistroMoroso = false;
    String Estatus;
    int n;
    int paginas;
    String NoPaga = "no";
    String Motivo = "";
    boolean seleccion = false;
    String idEntidad;
    String Placa, residenciaOld = "", vendedor = "";

    /** Creates new form */
    public PagosVehiculosLiberarFideicomisoFrame() {
        initComponents();
        sesion = new Sesion();
        /*
         * Fondo
         */

         
         
         

        jPanelFondo.setOpaque(false);
        setContentPane(jPanelFondo);
        /*
         * fondo
         */

        regimenBeans = new RegimenBeans();
        vehiculosBeans = new VehiculosBeans();
        comerciosBeans = new ComerciosBeans();
        contribuyentesBeans = new ContribuyentesBeans();
        vehiculosInscripcionBeans = new VehiculosInscripcionBeans();
        vehiculosTraspasoNumeracionBeans = new VehiculosTraspasoNumeracionBeans();
        regimenVehiculosBeans = new RegimenVehiculosBeans();
        recibesBeans = new RecibesBeans();
        recibesDetallesBeans = new RecibesDetallesBeans();
        recibesNumeracionBeans = new RecibesNumeracionBeans();
        java.util.Calendar ca = java.util.Calendar.getInstance();
        java.sql.Date mydate = new java.sql.Date(ca.getTimeInMillis());
        jFormattedTextFieldFecha.setValue(mydate);
        sesion.setTipoId("comercios");

        this.AnioRecibo = ca.get(java.util.Calendar.YEAR);
        NumeroMes = ca.get(java.util.Calendar.MONTH);



        jXDatePickerFechaFinFideicomiso.setDate(mydate);
        jXDatePickerFechaFinFideicomiso.setFormats(new SimpleDateFormat("dd/MM/yyyy"));
        sesion.setAnioRecibo(AnioRecibo);
        sesion.setNumeroMesRecibo(NumeroMes);
        //
        modelo = (DefaultTableModel) jXTable1.getModel();

        modelo.isCellEditable(1, 1);
        TableColumn columnCheckBox = jXTable1.getColumnModel().getColumn(0);
        columnCheckBox.setPreferredWidth(10);

        TableColumn columnId = jXTable1.getColumnModel().getColumn(1);
        columnId.setPreferredWidth(130);

        TableColumn columnRegimen = jXTable1.getColumnModel().getColumn(2);
        columnRegimen.setPreferredWidth(130);

        /*
         * Action del menu
         */

        menuPagar.addActionListener(new java.awt.event.ActionListener() {

            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jMenuItemPagarActionPerformed(evt);
            }
        });
        menuExonerar.addActionListener(new java.awt.event.ActionListener() {

            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jMenuItemExonerarActionPerformed(evt);
            }
        });






        menuEliminar.addActionListener(new java.awt.event.ActionListener() {

            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jMenuItemEliminarActionPerformed(evt);
            }
        });



        popupMenu.add(menuPagar);
        popupMenu.add(menuExonerar);
        popupMenu.add(separator0);
        popupMenu.add(menuEliminar);
        popupMenu.add(menuCerrar);
        // int NuevoNumeroRecibo = recibesBeans.getNumeroReciboDisponible();
        // if (NuevoNumeroRecibo != -1) {
        //   jTextFieldRecibo.setText(String.valueOf(NuevoNumeroRecibo));
        // }


        CargarExoneraciones(sesion.getIdmunicipio(), true);
        jTextFieldTotalExonerado.setText("");
        jTextFieldTotalPago.setText("");
        AutoCompleteDecorator.decorate(this.jComboBoxExoneracion);

       
        CrearNuevoRecibo();
        CargarImpuestos();



    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jPanelFondo = new javax.swing.JPanel();
        jPanel1 = new javax.swing.JPanel();
        jLabel2 = new javax.swing.JLabel();
        jTextFieldRecibo = new javax.swing.JTextField();
        jButtonNuevoRecibo = new javax.swing.JButton();
        jLabel3 = new javax.swing.JLabel();
        jFormattedTextFieldFecha = new javax.swing.JFormattedTextField();
        jButtonRegresar = new javax.swing.JButton();
        jComboBoxExoneracion = new javax.swing.JComboBox();
        jLabel1 = new javax.swing.JLabel();
        jLabel18 = new javax.swing.JLabel();
        jTextFieldTotalPago = new javax.swing.JTextField();
        jLabel6 = new javax.swing.JLabel();
        jTextFieldTotalExonerado = new javax.swing.JTextField();
        jButtonAgregarImpuestos = new javax.swing.JButton();
        jScrollPane2 = new javax.swing.JScrollPane();
        jXTable1 = new org.jdesktop.swingx.JXTable();
        jLabel4 = new javax.swing.JLabel();
        jTextFieldPlaca = new javax.swing.JTextField();
        jButtonBuscarVehiculos = new javax.swing.JButton();
        jLabel5 = new javax.swing.JLabel();
        jTextFieldMarca = new javax.swing.JTextField();
        jLabel7 = new javax.swing.JLabel();
        jTextFieldModelo = new javax.swing.JTextField();
        jLabel8 = new javax.swing.JLabel();
        jTextFieldColor = new javax.swing.JTextField();
        jPanel5 = new javax.swing.JPanel();
        jLabel16 = new javax.swing.JLabel();
        jRadioButtonContribuyente = new javax.swing.JRadioButton();
        jRadioButtonComercio = new javax.swing.JRadioButton();
        jLabel9 = new javax.swing.JLabel();
        jTextFieldId = new javax.swing.JTextField();
        jTextFieldDueno = new javax.swing.JTextField();
        jLabel10 = new javax.swing.JLabel();
        jButtonImprimir = new javax.swing.JButton();
        jButtonLimpiar = new javax.swing.JButton();
        jButtonRegresar2 = new javax.swing.JButton();
        jLabel11 = new javax.swing.JLabel();
        jLabel12 = new javax.swing.JLabel();
        jLabel13 = new javax.swing.JLabel();
        jXDatePickerFechaFinFideicomiso = new org.jdesktop.swingx.JXDatePicker();
        jLabel14 = new javax.swing.JLabel();
        jFormattedTextFieldFechaFideicomiso = new javax.swing.JFormattedTextField();
        jTextFieldEntidad = new javax.swing.JTextField();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
        setTitle("LIBERAR FIDEICOMISO DE VEHICULOS");
        addWindowFocusListener(new java.awt.event.WindowFocusListener() {
            public void windowGainedFocus(java.awt.event.WindowEvent evt) {
                formWindowGainedFocus(evt);
            }
            public void windowLostFocus(java.awt.event.WindowEvent evt) {
            }
        });

        jPanel1.setBorder(javax.swing.BorderFactory.createEtchedBorder());
         
        jPanel1.setPreferredSize(new java.awt.Dimension(1007, 800));

        jLabel2.setText("Recibo");

        jTextFieldRecibo.setToolTipText("Numero de recibo");
        jTextFieldRecibo.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jTextFieldReciboActionPerformed(evt);
            }
        });

        jButtonNuevoRecibo.setIcon(new javax.swing.ImageIcon(getClass().getResource("/gif/new.jpeg"))); // NOI18N
        jButtonNuevoRecibo.setToolTipText("Nuevo Recibo");
        jButtonNuevoRecibo.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButtonNuevoReciboActionPerformed(evt);
            }
        });

        jLabel3.setText("Fecha");

        jFormattedTextFieldFecha.setFormatterFactory(new javax.swing.text.DefaultFormatterFactory(new javax.swing.text.DateFormatter(new java.text.SimpleDateFormat("dd/MM/yyyy"))));
        jFormattedTextFieldFecha.setToolTipText("Fecha");
        jFormattedTextFieldFecha.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jFormattedTextFieldFechaActionPerformed(evt);
            }
        });

        jButtonRegresar.setIcon(new javax.swing.ImageIcon(getClass().getResource("/gif/regresar.jpeg"))); // NOI18N
        jButtonRegresar.setToolTipText("Regresar");
        jButtonRegresar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButtonRegresarActionPerformed(evt);
            }
        });

        jLabel1.setText("Exoneracion");

        jLabel18.setText("Total");

        jTextFieldTotalPago.setEnabled(false);
        jTextFieldTotalPago.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jTextFieldTotalPagoActionPerformed(evt);
            }
        });

        jLabel6.setText("Total Exonerado");

        jTextFieldTotalExonerado.setEnabled(false);

        jButtonAgregarImpuestos.setIcon(new javax.swing.ImageIcon(getClass().getResource("/gif/impuestos.png"))); // NOI18N
        jButtonAgregarImpuestos.setToolTipText("Agregar Impuestos");
        jButtonAgregarImpuestos.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButtonAgregarImpuestosActionPerformed(evt);
            }
        });

        jScrollPane2.setHorizontalScrollBarPolicy(javax.swing.ScrollPaneConstants.HORIZONTAL_SCROLLBAR_ALWAYS);
        jScrollPane2.setVerticalScrollBarPolicy(javax.swing.ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS);

        jXTable1.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {

            },
            new String [] {
                ".", "Codigo", "Regimen", "Deuda", "Pago", "Saldo", "Exoneracion", "Valor", "Comentario"
            }
        ) {
            Class[] types = new Class [] {
                java.lang.Boolean.class, java.lang.String.class, java.lang.String.class, java.lang.Double.class, java.lang.Double.class, java.lang.Double.class, java.lang.Double.class, java.lang.Double.class, java.lang.String.class
            };
            boolean[] canEdit = new boolean [] {
                true, false, false, false, true, true, true, false, true
            };

            public Class getColumnClass(int columnIndex) {
                return types [columnIndex];
            }

            public boolean isCellEditable(int rowIndex, int columnIndex) {
                return canEdit [columnIndex];
            }
        });
        jXTable1.setOpaque(false);
        jScrollPane2.setViewportView(jXTable1);

        jLabel4.setText("Placa");

        jTextFieldPlaca.setColumns(35);
        jTextFieldPlaca.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jTextFieldPlacaActionPerformed(evt);
            }
        });

        jButtonBuscarVehiculos.setIcon(new javax.swing.ImageIcon(getClass().getResource("/gif/search.png"))); // NOI18N
        jButtonBuscarVehiculos.setToolTipText("Buscar");
        jButtonBuscarVehiculos.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButtonBuscarVehiculosActionPerformed(evt);
            }
        });

        jLabel5.setText("Marca");

        jTextFieldMarca.setEditable(false);

        jLabel7.setText("Modelo");

        jTextFieldModelo.setEditable(false);

        jLabel8.setText("Color");

        jTextFieldColor.setEditable(false);

        jPanel5.setBorder(javax.swing.BorderFactory.createEtchedBorder());
        jPanel5.setEnabled(false);

        jLabel16.setText("Dueño Anterior");

        jRadioButtonContribuyente.setSelected(true);
        jRadioButtonContribuyente.setText("Contribuyente");
        jRadioButtonContribuyente.setEnabled(false);
        jRadioButtonContribuyente.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                jRadioButtonContribuyenteMouseClicked(evt);
            }
        });

        jRadioButtonComercio.setText("Comercio");
        jRadioButtonComercio.setEnabled(false);
        jRadioButtonComercio.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                jRadioButtonComercioMouseClicked(evt);
            }
        });

        javax.swing.GroupLayout jPanel5Layout = new javax.swing.GroupLayout(jPanel5);
        jPanel5.setLayout(jPanel5Layout);
        jPanel5Layout.setHorizontalGroup(
            jPanel5Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel5Layout.createSequentialGroup()
                .addComponent(jLabel16)
                .addGap(18, 18, 18)
                .addComponent(jRadioButtonContribuyente)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jRadioButtonComercio)
                .addContainerGap(49, Short.MAX_VALUE))
        );
        jPanel5Layout.setVerticalGroup(
            jPanel5Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jLabel16)
            .addGroup(jPanel5Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                .addComponent(jRadioButtonComercio)
                .addComponent(jRadioButtonContribuyente))
        );

        jLabel9.setText("Identificador");

        jTextFieldId.setEditable(false);

        jTextFieldDueno.setEditable(false);

        jLabel10.setText("Dueño");

        jButtonImprimir.setIcon(new javax.swing.ImageIcon(getClass().getResource("/gif/print.jpeg"))); // NOI18N
        jButtonImprimir.setToolTipText("Imprime el recibo");
        jButtonImprimir.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButtonImprimirActionPerformed(evt);
            }
        });

        jButtonLimpiar.setIcon(new javax.swing.ImageIcon(getClass().getResource("/gif/escoba.png"))); // NOI18N
        jButtonLimpiar.setToolTipText("Limpiar");
        jButtonLimpiar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButtonLimpiarActionPerformed(evt);
            }
        });

        jButtonRegresar2.setIcon(new javax.swing.ImageIcon(getClass().getResource("/gif/regresar.jpeg"))); // NOI18N
        jButtonRegresar2.setToolTipText("Regresar");
        jButtonRegresar2.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButtonRegresar2ActionPerformed(evt);
            }
        });

        jLabel11.setText("Entidad");

        jLabel12.setText("Fecha Fin Fideicomiso");

        jLabel13.setFont(new java.awt.Font("DejaVu Sans", 1, 13)); // NOI18N
        jLabel13.setText("Fideicomiso");

        jLabel14.setText("Fecha Fideicomiso");

        jFormattedTextFieldFechaFideicomiso.setEditable(false);
        jFormattedTextFieldFechaFideicomiso.setFormatterFactory(new javax.swing.text.DefaultFormatterFactory(new javax.swing.text.DateFormatter(new java.text.SimpleDateFormat("dd/MM/yyyy"))));
        jFormattedTextFieldFechaFideicomiso.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jFormattedTextFieldFechaFideicomisoActionPerformed(evt);
            }
        });

        jTextFieldEntidad.setEditable(false);
        jTextFieldEntidad.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jTextFieldEntidadActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addComponent(jLabel5)
                        .addGap(25, 25, 25)
                        .addComponent(jTextFieldMarca, javax.swing.GroupLayout.PREFERRED_SIZE, 291, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addComponent(jLabel2)
                        .addGap(18, 18, 18)
                        .addComponent(jTextFieldRecibo, javax.swing.GroupLayout.PREFERRED_SIZE, 100, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(jButtonNuevoRecibo)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(jLabel3)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(jFormattedTextFieldFecha, javax.swing.GroupLayout.PREFERRED_SIZE, 135, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(jButtonRegresar))
                    .addComponent(jPanel5, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addGap(108, 108, 108)
                        .addComponent(jLabel13))
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addContainerGap()
                        .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                            .addGroup(jPanel1Layout.createSequentialGroup()
                                .addComponent(jLabel10)
                                .addGap(54, 54, 54))
                            .addGroup(jPanel1Layout.createSequentialGroup()
                                .addComponent(jLabel9)
                                .addGap(18, 18, 18)))
                        .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(jTextFieldDueno, javax.swing.GroupLayout.PREFERRED_SIZE, 411, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(jTextFieldId, javax.swing.GroupLayout.PREFERRED_SIZE, 254, javax.swing.GroupLayout.PREFERRED_SIZE)))
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addComponent(jLabel4)
                        .addGap(18, 18, 18)
                        .addComponent(jTextFieldPlaca, javax.swing.GroupLayout.PREFERRED_SIZE, 173, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGap(18, 18, 18)
                        .addComponent(jButtonBuscarVehiculos, javax.swing.GroupLayout.PREFERRED_SIZE, 55, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addComponent(jLabel7)
                        .addGap(18, 18, 18)
                        .addComponent(jTextFieldModelo, javax.swing.GroupLayout.PREFERRED_SIZE, 311, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(jLabel8)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(jTextFieldColor, javax.swing.GroupLayout.PREFERRED_SIZE, 204, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addContainerGap()
                        .addComponent(jLabel18)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addGroup(jPanel1Layout.createSequentialGroup()
                                .addComponent(jTextFieldTotalPago, javax.swing.GroupLayout.PREFERRED_SIZE, 159, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addGap(18, 18, 18)
                                .addComponent(jLabel6)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(jTextFieldTotalExonerado, javax.swing.GroupLayout.PREFERRED_SIZE, 161, javax.swing.GroupLayout.PREFERRED_SIZE))
                            .addGroup(jPanel1Layout.createSequentialGroup()
                                .addComponent(jButtonImprimir, javax.swing.GroupLayout.PREFERRED_SIZE, 91, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addGap(18, 18, 18)
                                .addComponent(jButtonLimpiar, javax.swing.GroupLayout.PREFERRED_SIZE, 78, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addGap(26, 26, 26)
                                .addComponent(jButtonRegresar2, javax.swing.GroupLayout.PREFERRED_SIZE, 80, javax.swing.GroupLayout.PREFERRED_SIZE))))
                    .addComponent(jScrollPane2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addComponent(jButtonAgregarImpuestos, javax.swing.GroupLayout.PREFERRED_SIZE, 69, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(jLabel1)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(jComboBoxExoneracion, javax.swing.GroupLayout.PREFERRED_SIZE, 284, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addContainerGap()
                        .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(jLabel12)
                            .addComponent(jLabel14)
                            .addComponent(jLabel11))
                        .addGap(18, 18, 18)
                        .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(jXDatePickerFechaFinFideicomiso, javax.swing.GroupLayout.PREFERRED_SIZE, 200, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(jFormattedTextFieldFechaFideicomiso, javax.swing.GroupLayout.PREFERRED_SIZE, 211, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(jTextFieldEntidad, javax.swing.GroupLayout.PREFERRED_SIZE, 381, javax.swing.GroupLayout.PREFERRED_SIZE))))
                .addContainerGap(27, Short.MAX_VALUE))
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel2)
                    .addComponent(jTextFieldRecibo, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jButtonNuevoRecibo)
                    .addComponent(jLabel3)
                    .addComponent(jFormattedTextFieldFecha, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jButtonRegresar))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel4)
                    .addComponent(jTextFieldPlaca, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jButtonBuscarVehiculos))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jTextFieldMarca, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel5))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel7)
                    .addComponent(jTextFieldModelo, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel8)
                    .addComponent(jTextFieldColor, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(jPanel5, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addComponent(jLabel10)
                        .addGap(3, 3, 3))
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(jTextFieldId, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(jLabel9))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(jTextFieldDueno, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)))
                .addComponent(jLabel13)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel11)
                    .addComponent(jTextFieldEntidad, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(6, 6, 6)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jLabel14)
                    .addComponent(jFormattedTextFieldFechaFideicomiso, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel12)
                    .addComponent(jXDatePickerFechaFinFideicomiso, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addComponent(jButtonAgregarImpuestos, javax.swing.GroupLayout.PREFERRED_SIZE, 42, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                        .addComponent(jComboBoxExoneracion, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addComponent(jLabel1)))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jScrollPane2, javax.swing.GroupLayout.PREFERRED_SIZE, 107, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel18)
                    .addComponent(jLabel6)
                    .addComponent(jTextFieldTotalExonerado, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jTextFieldTotalPago, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jButtonImprimir, javax.swing.GroupLayout.PREFERRED_SIZE, 45, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jButtonLimpiar, javax.swing.GroupLayout.PREFERRED_SIZE, 45, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jButtonRegresar2, javax.swing.GroupLayout.PREFERRED_SIZE, 45, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addContainerGap())
        );

        javax.swing.GroupLayout jPanelFondoLayout = new javax.swing.GroupLayout(jPanelFondo);
        jPanelFondo.setLayout(jPanelFondoLayout);
        jPanelFondoLayout.setHorizontalGroup(
            jPanelFondoLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, 761, javax.swing.GroupLayout.PREFERRED_SIZE)
        );
        jPanelFondoLayout.setVerticalGroup(
            jPanelFondoLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, 640, javax.swing.GroupLayout.PREFERRED_SIZE)
        );

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jPanelFondo, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jPanelFondo, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

private void jButtonRegresarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButtonRegresarActionPerformed

    this.dispose();
}//GEN-LAST:event_jButtonRegresarActionPerformed

private void jButtonNuevoReciboActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButtonNuevoReciboActionPerformed

    CrearNuevoRecibo();
}//GEN-LAST:event_jButtonNuevoReciboActionPerformed

private void jFormattedTextFieldFechaActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jFormattedTextFieldFechaActionPerformed
}//GEN-LAST:event_jFormattedTextFieldFechaActionPerformed

private void jButtonRegresar2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButtonRegresar2ActionPerformed

    dispose();
}//GEN-LAST:event_jButtonRegresar2ActionPerformed

private void jButtonImprimirActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButtonImprimirActionPerformed


    try {
        if (ValidarEntradas() == false) {
            return;
        }


        /*
         * guardar el recibo
         * 
         */
        IdVehiculo = vehiculosBeans.getIdVehiculo();
        recibesNumeracionBeans.setActivo("si");
        recibesNumeracionBeans.setIdMunicipio(sesion.getIdmunicipio());
        recibesNumeracionBeans.setIdRecibo(IdRecibo);

        boolean guardado = recibesNumeracionBeans.Guardar();
        if (guardado == false) {
            sesion.MostrarMensajeAdvertencia("Advertencia", "No se pudo guardar la numeracion del recibo\nIntentelo nuevamente");
            return;
        }
        recibesBeans.setIdRecibo(IdRecibo);
        java.util.Date myFecha = (java.util.Date) jFormattedTextFieldFecha.getValue();
        java.sql.Date date = new java.sql.Date(myFecha.getTime());
        recibesBeans.setFecha(date);
        recibesBeans.setId(IdVehiculo);
        recibesBeans.setTipoId(TipoId);
        recibesBeans.setAnulado("no");
        recibesBeans.setExonerado("no");
        if (TieneExoneracion == true) {
            recibesBeans.setExonerado("si");
        }
        recibesBeans.setMoroso("no");
        if (TieneAlgunRegistroMoroso == true) {
            recibesBeans.setMoroso("si");
        }

        recibesBeans.setTotalPagado(TotalPagado);

        recibesBeans.setTotalExonerado(TotalExonerado);

        recibesBeans.setIdExonerado("");
        if (TieneExoneracion == true) {
            recibesBeans.setIdExonerado(idExoneracion);
        }
        recibesBeans.setTipoRecibo("vehiculosfideicomisoliberar");




        /*
         *cargar los datos del jxTable en arrays de sesion
         * esto permitira usarlos en los detalles de recibos
         * en los pagos mensuales
         * en las morosidades , vigencias y recargos
         *
         */

        recibesDetallesBeans.setIdRecibo(IdRecibo);
        int contadorRegistrosRecibos = -1;
        for (int i = 0; i < n; i++) {
            //this.idRegimen = String.valueOf(jXTable1.getValueAt(i, 1));          

            String SDeuda = String.valueOf(jXTable1.getValueAt(i, 3));
            if (SDeuda.equals("")) {
                Deuda = 0.0;
            } else {
                Deuda = Double.parseDouble(SDeuda);
            }
            String SPago = String.valueOf(jXTable1.getValueAt(i, 4));
            if (SPago.equals("")) {
                Pago = 0.0;
            } else {
                Pago = Double.parseDouble(SPago);
            }

            String SExoneracion = String.valueOf(jXTable1.getValueAt(i, 6));
            Exoneracion = 0.0;
            if (SExoneracion.equals("") || SExoneracion == null) {
                Exoneracion = 0.0;
            } else {
                Exoneracion = Double.parseDouble(SExoneracion);
            }

            if (Pago != 0 || Exoneracion != 0) {
                SaldoAnterior = 0.0;
                //no pago ni se exonero, no se toma en cuenta
                contadorRegistrosRecibos++;
                Saldo = Deuda - Pago - Exoneracion;
                //Verificamos que no sea negativo el saldo
                //Esto4 ocurre cuando se pagan meses de mas.
                if (Saldo < 0) {
                    Saldo = 0.0;
                }
                Double ValorImpuesto = 0.0;
                String SValorImpuesto = String.valueOf(jXTable1.getValueAt(i, 7));

                if (SValorImpuesto.equals("") || SValorImpuesto == null) {
                    ValorImpuesto = 0.0;
                } else {
                    ValorImpuesto = Double.parseDouble(SValorImpuesto);
                }

                Double Morosidad = 0.0;

                sesion.ArrayRecibosTableIdRegimen[contadorRegistrosRecibos] = String.valueOf(jXTable1.getValueAt(i, 1));
                sesion.ArrayRecibosTableRegimen[contadorRegistrosRecibos] = String.valueOf(jXTable1.getValueAt(i, 2));
                sesion.ArrayRecibosTableValor[contadorRegistrosRecibos] = ValorImpuesto;
                sesion.ArrayRecibosTableDeuda[contadorRegistrosRecibos] = Deuda;
                sesion.ArrayRecibosTablePagos[contadorRegistrosRecibos] = Pago;
                sesion.ArrayRecibosTableExoneracion[contadorRegistrosRecibos] = Exoneracion;
                sesion.ArrayRecibosTableSaldo[contadorRegistrosRecibos] = Saldo;
                sesion.ArrayRecibosTableEstatus[contadorRegistrosRecibos] = "";
                sesion.ArrayRecibosTablePeriodo[contadorRegistrosRecibos] = "";
                sesion.ArrayRecibosTableCantidad[contadorRegistrosRecibos] = 1;
                sesion.ArrayRecibosTableSoloMorosidad[contadorRegistrosRecibos] = Morosidad;
                Estatus = "vehiculosfideicomisoliberar";
                sesion.ArrayRecibosTableEsRecargo[contadorRegistrosRecibos] = "no";

                String Comentario = String.valueOf(jXTable1.getValueAt(i, 8));
                if (Comentario == null || Comentario.equals("")) {
                    Comentario = "";
                } else {
                    Comentario = "(" + Comentario + ")";
                }
                sesion.ArrayRecibosTableComentario[contadorRegistrosRecibos] = Comentario;
                sesion.ArrayRecibosTableSaldoAnterior[contadorRegistrosRecibos] = Deuda;
            }

        } //for

        //Ahora guardar el detalle del recibo

        sesion.setNumeroRegistrosRecibosTable(contadorRegistrosRecibos);
        int tmp = contadorRegistrosRecibos + 1;
        if (tmp > 7) {
            sesion.MostrarMensajeAdvertencia("Advertencia", "El sistema permite 7 impuestos por recibos\nPor favor trabaje con solo 7 impuestos\nRealize otro pago para los restantes");
            return;
        }

        if (tmp >= 1 && tmp <= 7) {
            paginas = 1;
        }
recibesBeans.setCedulaTesoreroMunicipal("");
recibesBeans.setIdReciboAuxiliar(0);
        recibesBeans.GuardarRecibo();
        recibesDetallesBeans.GuardarDetalleRecibo();


        sesion.con.close();

        GuardarLiberacionFideicomiso();

//        if (paginas == 1) {
//            seleccion = jRadioButtonContribuyente.isSelected();
//            if (seleccion == true) {
//                reportSource = sesion.getRutaReportes() + "RecibosVehiculosGeneralContribuyentes.jrxml";
//            } else {
//                reportSource = sesion.getRutaReportes() + "RecibosVehiculosGeneralComercios.jrxml";
//            }
//
//
//
//            ImprimirRecibo();
//
//        }
PrinterRecibos pr = new PrinterRecibos();
        pr.setIdmunicipio(Sesion.getIdmunicipio());
        pr.setIdrecibo(IdRecibo);
        pr.setMunicipio(Sesion.getMunicipio());
        pr.setPaginas(paginas);
        pr.ImprimirRecibo();
        jButtonImprimir.setEnabled(false);



    } catch (Exception ex) {
        sesion.MostrarMensajeError("Error ", "Metodo:  jButtonImprimirActionPerformed()\n " + ex.getMessage().toString());
    }

}//GEN-LAST:event_jButtonImprimirActionPerformed

    private void ImprimirRecibo() {
        try {


            Map<String, Object> params = new HashMap<String, Object>();


            if (sesion.Conectar() == false) {
                JOptionPane.showMessageDialog(this, "No se pudo establecer la conexion", "Mensaje", JOptionPane.INFORMATION_MESSAGE);
                return;
            }
            JasperReport jasperReport =
                    JasperCompileManager.compileReport(reportSource);
            params.put("P_IDVEHICULO", Integer.parseInt(this.IdVehiculo));
            params.put("P_IDMUNICIPIO", sesion.getIdmunicipio());
            params.put("P_MUNICIPIO", sesion.getMunicipio());
            params.put("P_NOMBREUSUARIO", sesion.getUsuario());
            params.put("P_IDRECIBO", IdRecibo);
            params.put("P_TITULO", "Por los conceptos, importes y periodos que se detallan (Liberacion de Fideicomiso Vehicular)");

            JasperPrint jasperPrint =
                    JasperFillManager.fillReport(
                    jasperReport, params, sesion.con);

            JasperViewer.viewReport(jasperPrint, false);
        } catch (Exception ex) {
            sesion.MostrarMensajeError("Error ", "ImprimirUnaPagina()\n " + ex.getMessage().toString());
        }
    }
private void jTextFieldTotalPagoActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jTextFieldTotalPagoActionPerformed
}//GEN-LAST:event_jTextFieldTotalPagoActionPerformed

private void jButtonLimpiarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButtonLimpiarActionPerformed

    Limpiar();
    CrearNuevoRecibo();
}//GEN-LAST:event_jButtonLimpiarActionPerformed

    private void Actualizar() {
        try {

            jTextFieldPlaca.setText(vehiculosBeans.getPlaca());
            this.Placa = vehiculosBeans.getPlaca();
            jTextFieldMarca.setText(vehiculosBeans.getMarca());
            jTextFieldModelo.setText(vehiculosBeans.getModelo());
            jTextFieldColor.setText(vehiculosBeans.getColor());
            jTextFieldId.setText(vehiculosBeans.getId());
            jTextFieldDueno.setText(vehiculosBeans.getDueno());
            this.vendedor = vehiculosBeans.getDueno();

            String TipoId = vehiculosBeans.getTipoId();
            String idOld = vehiculosBeans.getId();
            TipoId = TipoId.toLowerCase();
            if (TipoId.equals("contribuyentes")) {
                jRadioButtonContribuyente.setSelected(true);
                jRadioButtonComercio.setSelected(false);

            } else {
                if (TipoId.equals("comercios")) {
                    jRadioButtonContribuyente.setSelected(false);
                    jRadioButtonComercio.setSelected(true);

                }
            }
            LimpiarTable();
            CargarImpuestos();
            CrearNuevoRecibo();
            CargarExoneraciones(sesion.getIdmunicipio(), true);
            CargarEntidad();
            repaint();

        } catch (Exception ex) {
            JOptionPane.showMessageDialog(this, "Error " + ex.getMessage(), "Error", JOptionPane.ERROR_MESSAGE);
        }
    }

private void jTextFieldReciboActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jTextFieldReciboActionPerformed
}//GEN-LAST:event_jTextFieldReciboActionPerformed

private void formWindowGainedFocus(java.awt.event.WindowEvent evt) {//GEN-FIRST:event_formWindowGainedFocus
    // TODO add your handling code here:
    this.jTextFieldRecibo.setEnabled(false);
    try {

        if (focoImpuesto) {
            if (sesion.getSeleccionado().equals("si")) {
                AgregarImpuestoTabla();
            }
        } else {
            if (focoVehiculo) {
                Actualizar();
            }

        }
        focoImpuesto = false;
        focoVehiculo = false;
    } catch (Exception ex) {
        sesion.MostrarMensajeError("Error ", "formWindowGainedFocus()\nError " + ex.getMessage().toString());
    }
}//GEN-LAST:event_formWindowGainedFocus

private void jButtonAgregarImpuestosActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButtonAgregarImpuestosActionPerformed
    // TODO add your handling code here:
    try {
        ImpuestosAgregarFrame impuestosAgregarFrame = new ImpuestosAgregarFrame();
        impuestosAgregarFrame.setLocationRelativeTo(null);
        impuestosAgregarFrame.setVisible(true);
        focoImpuesto = true;
        focoVehiculo = false;

    } catch (Exception ex) {
        sesion.MostrarMensajeError("Error ", "Metodo: jButtonAgregarImpuestosActionPerformed()\n " + ex.getMessage().toString());
    }
}//GEN-LAST:event_jButtonAgregarImpuestosActionPerformed

private void jTextFieldPlacaActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jTextFieldPlacaActionPerformed

    CargarVehiculos();
}//GEN-LAST:event_jTextFieldPlacaActionPerformed

private void jButtonBuscarVehiculosActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButtonBuscarVehiculosActionPerformed

    VehiculosFideicomisoFrame vehiculosFideicomisoFrame = new VehiculosFideicomisoFrame();
    vehiculosFideicomisoFrame.setLocationRelativeTo(null);
    vehiculosFideicomisoFrame.setVisible(true);
    focoVehiculo = true;
}//GEN-LAST:event_jButtonBuscarVehiculosActionPerformed

private void jRadioButtonContribuyenteMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jRadioButtonContribuyenteMouseClicked
}//GEN-LAST:event_jRadioButtonContribuyenteMouseClicked

private void jRadioButtonComercioMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jRadioButtonComercioMouseClicked
}//GEN-LAST:event_jRadioButtonComercioMouseClicked

private void jFormattedTextFieldFechaFideicomisoActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jFormattedTextFieldFechaFideicomisoActionPerformed
    // TODO add your handling code here:
}//GEN-LAST:event_jFormattedTextFieldFechaFideicomisoActionPerformed

private void jTextFieldEntidadActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jTextFieldEntidadActionPerformed
    // TODO add your handling code here:
}//GEN-LAST:event_jTextFieldEntidadActionPerformed

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        java.awt.EventQueue.invokeLater(new Runnable() {

            public void run() {
                new PagosVehiculosLiberarFideicomisoFrame().setVisible(true);
            }
        });
    }

    /*
     * 
     *verifica si ya se pago la placa para este año 
     * 
     */
    public void CargarImpuestos() {
        try {
            this.IdVehiculo = jTextFieldPlaca.getText();

            this.jXTable1.setModel(modelo);
            jXTable1.setVisible(true);
            TableColumn column = jXTable1.getColumnModel().getColumn(4);
            fieldPago = new JTextField();

            fieldPago.addActionListener(new java.awt.event.ActionListener() {

                public void actionPerformed(java.awt.event.ActionEvent evt) {
                    jTextFieldPagoActionPerformed(evt);
                }
            });





            column.setCellEditor(new DefaultCellEditor(fieldPago));

            /*
             * JTextField para el Saldo
             */

            TableColumn columnSaldo = jXTable1.getColumnModel().getColumn(5);
            fieldSaldo = new JTextField();
            fieldSaldo.setEditable(false);
            fieldSaldo.addActionListener(new java.awt.event.ActionListener() {

                public void actionPerformed(java.awt.event.ActionEvent evt) {
                    jTextFieldSaldoActionPerformed(evt);
                }
            });

            columnSaldo.setCellEditor(new DefaultCellEditor(fieldSaldo));
            /*
             * JTextField para la exoneracion
             */

            TableColumn columnExoneracion = jXTable1.getColumnModel().getColumn(6);
            fieldExoneracion = new JTextField();

            fieldExoneracion.addActionListener(new java.awt.event.ActionListener() {

                public void actionPerformed(java.awt.event.ActionEvent evt) {
                    jTextFieldExoneracionActionPerformed(evt);
                }
            });
            columnExoneracion.setCellEditor(new DefaultCellEditor(fieldExoneracion));


            TableColumn columnPopup = jXTable1.getColumnModel().getColumn(8);

            this.jXTable1.addMouseListener(new MouseAdapter() {

                public void mouseClicked(MouseEvent e) {
                    if (SwingUtilities.isRightMouseButton(e)) {
                        popupMenu.show(jXTable1, e.getX(), e.getY());
                    }

                    fila = jXTable1.rowAtPoint(e.getPoint());
                    int columna = jXTable1.columnAtPoint(e.getPoint());
                    if ((fila > -1) && (columna > -1)) {
                        String idRegimen = String.valueOf(jXTable1.getValueAt(fila, 1));
                        String regimen = String.valueOf(jXTable1.getValueAt(fila, 2));
                        String SDeuda = String.valueOf(jXTable1.getValueAt(fila, 3));
                        Valor = Double.parseDouble(SDeuda);
                        String periodoPago = String.valueOf(jXTable1.getValueAt(fila, 4));
                        String mesPago = String.valueOf(jXTable1.getValueAt(fila, 5));
                        regimenVehiculosBeans.setIdRegimen(idRegimen);
                        regimenVehiculosBeans.setRegimen(regimen);
                        regimenVehiculosBeans.setValor(Valor);
                        regimenVehiculosBeans.setPeriodoPago(periodoPago);
                        regimenVehiculosBeans.setMesPago(mesPago);


                    }
                }
            });



        } catch (Exception ex) {

            sesion.MostrarMensajeError("Error ", "CargarImpuestos()\n " + ex.getMessage().toString());
        }

    }

    private boolean VerificarSiFueAgregado() {
        try {
//            String idRegimen = (String) jTextFieldIdRegimen.getText();
            int n = jXTable1.getRowCount();
            if (n < 0) {
                JOptionPane.showMessageDialog(this, "Numero de filas negativo ", "Error", JOptionPane.ERROR_MESSAGE);
                return false;
            }

            for (int i = 0; i < n; i++) {

                String idRegimenTable = String.valueOf(jXTable1.getValueAt(i, 1));
                if (idRegimenTable.equals(rowIdRegimen)) {
                    return true;
                }

            }

            return false;
        } catch (Exception ex) {
            sesion.MostrarMensajeError("Error ", "VerificarSiFueAgregado()\n " + ex.getMessage().toString());
        }
        return true;

    }

    private void LimpiarComercios() {
        jTextFieldPlaca.setText("");
        jTextFieldMarca.setText("");
        jTextFieldModelo.setText("");
        jTextFieldColor.setText("");
        jTextFieldId.setText("");
        jTextFieldDueno.setText("");
    }

    private void Limpiar() {
        try {
            jTextFieldRecibo.setText("");
            jTextFieldTotalPago.setText("");
            LimpiarRegimen();
            LimpiarComercios();
            LimpiarTable();
        } catch (Exception ex) {
            sesion.MostrarMensajeError("Error ", "Limpiar()\n " + ex.getMessage().toString());
        }
    }

    public void LimpiarRegimen() {
        //jTextFieldIdRegimen.setText("");
    }

    private void CalcularTotalPagado() {
        try {
            Valor = 0.0;
            Double TotalPagado = 0.0;
            int n = jXTable1.getRowCount();
            jTextFieldTotalPago.setText("");
            for (int i = 0; i < n; i++) {

                String SValor = String.valueOf(jXTable1.getValueAt(i, 4));
                if (SValor.equals("")) {
                    Valor = 0.0;
                } else {
                    Valor = Double.parseDouble(SValor);
                    TotalPagado += Valor;
                }
            }
            
 jTextFieldTotalPago.setText(sesion.getFormateador().format(TotalPagado));
            if (TotalPagado >= 0) {
                jButtonImprimir.setEnabled(true);
            }
        } catch (Exception ex) {
            sesion.MostrarMensajeError("Error ", "CalcularTotalPagado()\n " + ex.getMessage().toString());
        }
    }

    private void CalcularTotalExonerado() {
        try {
            Valor = 0.0;
            Double TotalPagado = 0.0;
            int n = jXTable1.getRowCount();
            jTextFieldTotalExonerado.setText("");
            for (int i = 0; i < n; i++) {

                String SValor = String.valueOf(jXTable1.getValueAt(i, 6));
                if (SValor.equals("")) {
                    Valor = 0.0;
                } else {
                    Valor = Double.parseDouble(SValor);
                    TotalPagado += Valor;
                }
            }
                        
            jTextFieldTotalExonerado.setText(sesion.getFormateador().format(TotalPagado));
            if (TotalPagado >= 0) {
                jButtonImprimir.setEnabled(true);
            }
        } catch (Exception ex) {
            sesion.MostrarMensajeError("Error ", "CalcularTotalExonerado()\n " + ex.getMessage().toString());


        }
    }

    /*
     * agregar fila
     * 
     */
    private void LimpiarTable() {
        try {

            boolean control = false;
            while (control == false) {
                int n = jXTable1.getRowCount();
                if (n <= 0) {
                    control = true;
                } else {
                    modelo.removeRow(0);
                }

            }//while
        } catch (Exception ex) {
            sesion.MostrarMensajeError("Error ", "LimpiarTable()\n " + ex.getMessage().toString());
        }
    }

    /*
     *-----------------------------------------
     *              Cargar                    *
     *-----------------------------------------
     */
    private void AgregarFila() {
        try {
            Object[] filas = new Object[9]; // Hay tres columnas en la tabla
            rowComentario = "";
            filas[0] = new Boolean(false);
            filas[1] = rowIdRegimen;
            filas[2] = rowRegimen;
            filas[3] = rowDeuda;
            filas[4] = rowPago;
            filas[5] = rowSaldo;
            filas[6] = rowExoneracion;
            //      filas[7] = rowTipo;
            //    filas[8] = rowDetalle.toLowerCase();
            filas[7] = rowValor;
            //    filas[10] = rowMorosidad;
            filas[8] = rowComentario;
            modelo.addRow(filas);
        } catch (Exception ex) {
            sesion.MostrarMensajeError("Error ", "AgregarFila()\n " + ex.getMessage().toString());
        }
    }

    /*
     *
     * Cargar exoneraciones
     *
     */
    public void CargarExoneraciones(String idMunicipio, boolean comboCorregimientoActual) {
        try {
            if (sesion.Conectar() == false) {
                JOptionPane.showMessageDialog(this, "No se pudo establecer la conexion", "Mensaje", JOptionPane.INFORMATION_MESSAGE);
                return;
            }

            String sqlquery = "select *  from exoneraciones where idmunicipio = ? and activo='si'  and year(fechaexoneracion)='" + AnioRecibo + "'";
            PreparedStatement psquery = sesion.con.prepareStatement(sqlquery);
            psquery.setString(1, idMunicipio);
            ResultSet rs = psquery.executeQuery();

            jComboBoxExoneracion.removeAllItems();


            int count = 0;
            jComboBoxExoneracion.insertItemAt("no exonerado", count);
            count++;
            while (rs.next()) {
                String idexoneracion = rs.getString("idexoneracion");
                jComboBoxExoneracion.insertItemAt(idexoneracion, count);
                count++;
            }
            jComboBoxExoneracion.setSelectedIndex(0);
        } catch (Exception ex) {
            sesion.MostrarMensajeError("Error ", "CargarExoneraciones()\n " + ex.getMessage().toString());
        }
    }

    private void jTextFieldPagoActionPerformed(java.awt.event.ActionEvent evt) {

        try {

            String tmp = this.fieldPago.getText();
            if (tmp == null || tmp.equals("")) {
                sesion.MostrarMensajeAdvertencia("Pago incorrecto", "Ingrese el pago adecuado");
                return;
            }

            Pago = Double.parseDouble(tmp);
            ControlarPago();


        } catch (Exception ex) {
            sesion.MostrarMensajeError("Error ", "jTextFieldPagoActionPerformed()\n " + ex.getMessage().toString());
        }

    }

    private void ControlarPago() {
        try {
            fila = jXTable1.getSelectedRow();
            if (fila == -1) {
                JOptionPane.showMessageDialog(this, "No se selecciono ninguna fila", "Mensaje", JOptionPane.WARNING_MESSAGE);
                return;
            }

            String tmp = String.valueOf(jXTable1.getValueAt(fila, 3));
            Double Deuda = Double.parseDouble(tmp);
            tmp = String.valueOf(jXTable1.getValueAt(fila, 5));
            Double Saldo = Double.parseDouble(tmp);
            tmp = String.valueOf(jXTable1.getValueAt(fila, 6));
            Exoneracion = Double.parseDouble(tmp);
            String estatus = String.valueOf(jXTable1.getValueAt(fila, 7));
            estatus = estatus.toLowerCase();
            if (Pago < 0) {
                JOptionPane.showMessageDialog(this, "El pago no puede ser negativo", "Mensaje", JOptionPane.WARNING_MESSAGE);
                jXTable1.setValueAt(0.0, fila, 4);
                Saldo = Deuda - Exoneracion;
                if (Saldo < 0) {
                    Saldo = 0.0;
                }
                jXTable1.setValueAt(Saldo, fila, 5);
                return;
            }
            if (estatus.equals("recargo")) {
                if (Pago > Deuda) {
                    JOptionPane.showMessageDialog(this, "No puede pagar más del recargo asignado", "Mensaje", JOptionPane.WARNING_MESSAGE);
                    jXTable1.setValueAt(0.0, fila, 4);

                    return;
                }
            }
            Saldo = Deuda - Pago - Exoneracion;
            if (Saldo < 0) {
                Saldo = 0.0;
            }

            jXTable1.setValueAt(Saldo, fila, 5);

            jXTable1.repaint();
            modelo.fireTableDataChanged();
            CalcularTotalPagado();

        } catch (Exception ex) {
            sesion.MostrarMensajeError("Error ", "ControlarPago()\n " + ex.getMessage().toString());
        }
    }

    private void ControlarExoneracion() {
        try {

            String tmp = String.valueOf(jXTable1.getValueAt(fila, 3));
            Double Deuda = Double.parseDouble(tmp);
            tmp = String.valueOf(jXTable1.getValueAt(fila, 4));
            Pago = Double.parseDouble(tmp);
            tmp = String.valueOf(jXTable1.getValueAt(fila, 5));
            Double Saldo = Double.parseDouble(tmp);

            if (Exoneracion < 0) {
                JOptionPane.showMessageDialog(this, "La exoneracion  no puede ser negativo", "Mensaje", JOptionPane.WARNING_MESSAGE);
                jXTable1.setValueAt(0.0, fila, 6);
                Saldo = Deuda - Pago;
                if (Saldo < 0) {
                    Saldo = 0.0;
                }
                jXTable1.setValueAt(Saldo, fila, 5);
                return;
            }
            /*
            if (Exoneracion > Saldo) {
                JOptionPane.showMessageDialog(this, "La exoneracion  no puede ser mayor que el saldo pendiente", "Mensaje", JOptionPane.WARNING_MESSAGE);
                jXTable1.setValueAt(0.0, fila, 6);
                Saldo = Deuda - Pago;
                if (Saldo < 0) {
                    Saldo = 0.0;
                }
                jXTable1.setValueAt(Saldo, fila, 5);
                return;
            }
*/
            Saldo = Deuda - Pago - Exoneracion;
            if (Saldo < 0) {
                Saldo = 0.0;
            }
            jXTable1.setValueAt(Saldo, fila, 5);
            jXTable1.repaint();
            modelo.fireTableDataChanged();
            CalcularTotalExonerado();

        } catch (Exception ex) {
            sesion.MostrarMensajeError("Error ", "ControlarExoneracion()\n " + ex.getMessage().toString());
        }

    }

    private void jTextFieldExoneracionActionPerformed(java.awt.event.ActionEvent evt) {

        try {

            //falta validar el saldo no se debe modificar por el usuario
            fila = jXTable1.getSelectedRow();
            if (fila == -1) {
                JOptionPane.showMessageDialog(this, "No se selecciono ninguna fila", "Mensaje", JOptionPane.WARNING_MESSAGE);
                return;
            }
            String tmp = this.fieldExoneracion.getText();
            Exoneracion = Double.parseDouble(tmp);
            ControlarExoneracion();


        } catch (Exception ex) {
            sesion.MostrarMensajeError("Error ", "jTextFieldExoneracionActionPerformed()\n " + ex.getMessage().toString());
        }

    }

    private void jTextFieldSaldoActionPerformed(java.awt.event.ActionEvent evt) {

        try {

            //falta validar el saldo no se debe modificar por el usuario
            fila = jXTable1.getSelectedRow();
            if (fila == -1) {
                JOptionPane.showMessageDialog(this, "No se selecciono ninguna fila", "Mensaje", JOptionPane.WARNING_MESSAGE);
                return;
            }
            String tmp = String.valueOf(jXTable1.getValueAt(fila, 3));
            Double Deuda = Double.parseDouble(tmp);
            tmp = String.valueOf(jXTable1.getValueAt(fila, 4));
            Pago = Double.parseDouble(tmp);
            tmp = String.valueOf(jXTable1.getValueAt(fila, 6));
            Exoneracion = Double.parseDouble(tmp);
            if (Pago < 0) {
                JOptionPane.showMessageDialog(this, "El pago no puede ser negativo", "Mensaje", JOptionPane.WARNING_MESSAGE);
                jXTable1.setValueAt(0.0, fila, 4);
                return;
            }

            Double Saldo = Deuda - Pago - Exoneracion;
            if (Saldo < 0) {
                Saldo = 0.0;
            }
            // fieldSaldo.setText(String.valueOf(Saldo));
            jXTable1.setValueAt(Saldo, fila, 5);
            jXTable1.repaint();
            modelo.fireTableDataChanged();
            CalcularTotalPagado();
            CalcularTotalExonerado();
        } catch (Exception ex) {
            sesion.MostrarMensajeError("Error ", "jTextFieldSaldoActionPerformed()\n " + ex.getMessage().toString());
        }
    }

    private void jMenuItemPagarActionPerformed(java.awt.event.ActionEvent evt) {

        try {
            fila = jXTable1.getSelectedRow();
            if (fila == -1) {
                JOptionPane.showMessageDialog(this, "No se selecciono ninguna fila", "Mensaje", JOptionPane.WARNING_MESSAGE);
                return;
            }
            String sSaldo = String.valueOf(jXTable1.getValueAt(fila, 5));
            String tmp = JOptionPane.showInputDialog(null,
                    "Ingrese el Pago?", sSaldo);
            if (tmp == null || tmp.equals("")) {
                sesion.MostrarMensajeAdvertencia("Mensaje", "Ingrese la cantidad a pagar");
                return;
            }
            Pago = Double.parseDouble(tmp);

            this.fieldPago.setText(tmp);
            jXTable1.setValueAt(tmp, fila, 4);



            ControlarPago();


        } catch (Exception ex) {
            sesion.MostrarMensajeError("Error ", "jMenuItemPagarActionPerformed()\n " + ex.getMessage().toString());
        }
    }

    private void jMenuItemExonerarActionPerformed(java.awt.event.ActionEvent evt) {

        try {
            fila = jXTable1.getSelectedRow();
            if (fila == -1) {
                JOptionPane.showMessageDialog(this, "No se selecciono ninguna fila", "Mensaje", JOptionPane.WARNING_MESSAGE);
                return;
            }
            String sSaldo = String.valueOf(jXTable1.getValueAt(fila, 5));
            String tmp = JOptionPane.showInputDialog(null,
                    "Ingrese la cantidad a exonerar?", sSaldo);
            if (tmp == null || tmp.equals("")) {
                sesion.MostrarMensajeAdvertencia("Mensaje", "Ingrese la cantidad a pagar");
                return;
            }
            Exoneracion = Double.parseDouble(tmp);

            this.fieldExoneracion.setText(tmp);
            jXTable1.setValueAt(tmp, fila, 6);



            ControlarExoneracion();


        } catch (Exception ex) {
            sesion.MostrarMensajeError("Error ", "jMenuItemExonerarActionPerformed()\n " + ex.getMessage().toString());
        }
    }

    private boolean ValidarEntradas() {
        try {
            String SRecibo = this.jTextFieldRecibo.getText();
            if (SRecibo == null || SRecibo.equals("")) {
                JOptionPane.showMessageDialog(this, "Seleccione un vehiculo", "Mensaje", JOptionPane.INFORMATION_MESSAGE);
                jTextFieldRecibo.requestFocus();
                return false;
            }
            this.IdRecibo = Integer.parseInt(SRecibo);
            if (IdRecibo <= 0) {
                JOptionPane.showMessageDialog(this, "Seleccione un vehiculo", "Mensaje", JOptionPane.INFORMATION_MESSAGE);
                jTextFieldRecibo.requestFocus();
                return false;
            }

            IdVehiculo = this.jTextFieldPlaca.getText();

            if (IdVehiculo == null || IdVehiculo.equals("")) {
                JOptionPane.showMessageDialog(this, "No ha seleccionado un vehiculo", "Mensaje", JOptionPane.INFORMATION_MESSAGE);
                jTextFieldPlaca.requestFocus();
                return false;
            }


            String Marca = this.jTextFieldMarca.getText();
            if (Marca == null || Marca.equals("")) {
                JOptionPane.showMessageDialog(this, "No ha seleccionado ningun vehiculo", "Mensaje", JOptionPane.INFORMATION_MESSAGE);
                jTextFieldPlaca.requestFocus();
                return false;
            }


            String sTotalPagado = this.jTextFieldTotalPago.getText();
            String sTotalExonerado = this.jTextFieldTotalExonerado.getText();
            if ((sTotalPagado == null || sTotalPagado.equals("")) && (sTotalExonerado == null || sTotalExonerado.equals(""))) {
                JOptionPane.showMessageDialog(this, "No se ha pagado ni exonerado ningun impuesto", "Mensaje", JOptionPane.INFORMATION_MESSAGE);
                jTextFieldRecibo.requestFocus();
                return false;
            }
            TotalExonerado = 0.0;
            idExoneracion = String.valueOf(jComboBoxExoneracion.getSelectedItem());
            if (sTotalExonerado == null || sTotalExonerado.equals("")) {
                TotalExonerado = 0.0;
            } else {
                TotalExonerado = Double.parseDouble(sTotalExonerado);
                if (TotalExonerado > 0) {

                    if (idExoneracion.equals("no exonerado")) {
                        sesion.MostrarMensajeAdvertencia("Mensaje", "Debe seleccionar la exoneración\n ya que se exoneraron algunos impuestos");
                        return false;
                    }
                    TieneExoneracion = true;
                }
            }

            /*
             *Evaluar cuando selecciona una exoneracion y no marca ningun valor exonerado
             *
             */
            if (idExoneracion.equals("no exonerado")) {
                //nada
                TieneExoneracion = false;
            } else {
                if (TotalExonerado == 0) {
                    sesion.MostrarMensajeAdvertencia("Mensaje", "Se selecciono una exoneracion \n pero no se ha exonerado ningun impuesto");
                    return false;
                } else {
                    TieneExoneracion = true;
                }
            }


            TotalPagado = 0.0;
            if (sTotalPagado == null || sTotalPagado.equals("")) {
                TotalPagado = 0.0;
            } else {
                TotalPagado = Double.parseDouble(this.jTextFieldTotalPago.getText());
            }



            String sFecha = jFormattedTextFieldFecha.getText();
            if (sFecha == null || sFecha.equals("")) {
                JOptionPane.showMessageDialog(this, "seleccione la fecha ", "Mensaje", JOptionPane.INFORMATION_MESSAGE);
                jFormattedTextFieldFecha.requestFocus();
            }

            n = jXTable1.getRowCount();
            if (n == -1) {
                JOptionPane.showMessageDialog(this, "No se ha pagado ni exonerado ningun impuesto", "Mensaje", JOptionPane.INFORMATION_MESSAGE);
                return false;
            }
            int procesados = -1;
            for (int i = 0; i < n; i++) {
                String tmp = String.valueOf(jXTable1.getValueAt(i, 4));
                if (tmp == null || tmp.equals("") || tmp.equals("0.0")) {
                    //quiere decir que no pago impuesto
                    //verificar si fue exonerado
                    tmp = String.valueOf(jXTable1.getValueAt(i, 6));
                    if (tmp == null || tmp.equals("") || tmp.equals("0.0")) {
                        //tampoco se exonero
                    } else {
                        procesados++;
                    }
                } else {
                    //pago el impuesto
                    procesados++;
                }

                tmp = String.valueOf(jXTable1.getValueAt(i, 7));
                Estatus = tmp.toString();
                Estatus = Estatus.toLowerCase();
                if (Estatus.equals("morosidad")) {
                    TieneAlgunRegistroMoroso = true;
                }

            } //for
            if (procesados == -1) {
                JOptionPane.showMessageDialog(this, "No hay ningun impuesto asignado ", "Mensaje", JOptionPane.WARNING_MESSAGE);
                return false;
            }
            if (procesados >= sesion.getNumeroMaximoRegistrosPorRecibo()) {
                String tabString = "Por razones del tamaño del recibo \n  Solo se permiten " + sesion.getRegistrosPorRecibo() + " impuestos\n Quite algunos y generelos en otro recibo ";
                sesion.MostrarMensajeAdvertencia("Demasiados impuestos", tabString);
                return false;
            }


            return true;
        } catch (Exception ex) {
            sesion.MostrarMensajeError("Error ", "ValidarEntradas()\n " + ex.getMessage().toString());
        }
        return false;
    }

    private void CrearNuevoRecibo() {
        try {
            //  int NuevoNumeroRecibo = recibesBeans.getNumeroReciboDisponible();

            int NuevoNumeroRecibo = recibesNumeracionBeans.ReciboUltimo();
            if (NuevoNumeroRecibo != -1) {
                NuevoNumeroRecibo++;
                jTextFieldRecibo.setText(String.valueOf(NuevoNumeroRecibo));
                jButtonImprimir.setEnabled(true);
                jTextFieldTotalExonerado.setText("0.0");
                jTextFieldTotalPago.setText("0.0");
                jComboBoxExoneracion.setSelectedIndex(0);
                //coloco en cero en contador de recibos interno
                sesion.setNumeroRegistrosRecibosTable(0);
            } else {
                sesion.MostrarMensajeInformacion("Mensaje", "Debe registrar la numeracion inicial de recibos\n Disponible en el menu recibos");
            }
        } catch (Exception ex) {
            sesion.MostrarMensajeError("Error ", "CrearNuevoRecibo()\n " + ex.getMessage().toString());
        }
    }

    private void AgregarImpuestoTabla() {
        try {


            rowIdRegimen = regimenBeans.getIdRegimen();
            if (VerificarSiFueAgregado() == true) {
                JOptionPane.showMessageDialog(null, "Este impuesto ya fue agregado al recibo", "Mensaje", JOptionPane.INFORMATION_MESSAGE);
                return;
            }
            regimenBeans.getIdSubGrupoRegimen();
            rowRegimen = regimenBeans.getRegimen();
            rowValor = regimenBeans.getValor();
            rowCantidad = 1;
            rowDeuda = regimenBeans.getValor();
            rowPago = 0.0;
            rowSaldo = rowDeuda;
            rowExoneracion = 0.0;

            rowDetalle = "";
            AgregarFila();
        } catch (Exception ex) {
            sesion.MostrarMensajeError("Error ", "AgregarImpuestoTabla()\n " + ex.getMessage().toString());
        }
    }

    private void jMenuItemEliminarActionPerformed(java.awt.event.ActionEvent evt) {

        try {
            ///
            //Elimino una fila de la tabla
            fila = jXTable1.getSelectedRow();
            if (fila == -1) {
                JOptionPane.showMessageDialog(this, "No se selecciono ninguna fila", "Mensaje", JOptionPane.WARNING_MESSAGE);
                return;
            }
            modelo.removeRow(fila);

            int n2 = jXTable1.getRowCount();
            if (n2 == -1) {
                JOptionPane.showMessageDialog(this, "No se ha registrado ningun impuesto a pagar", "Mensaje", JOptionPane.INFORMATION_MESSAGE);
                return;
            }




            String[] arrayCodigo = new String[n2];
            String[] arrayRegimen = new String[n2];
            String[] arrayDeuda = new String[n2];
            String[] arrayPago = new String[n2];
            String[] arraySaldo = new String[n2];
            String[] arrayExoneracion = new String[n2];
            String[] arrayValor = new String[n2];
            String[] arrayComentario = new String[n2];

            int procesados = -1;
            for (int i = 0; i < n2; i++) {
                String tmp = String.valueOf(jXTable1.getValueAt(i, 1));
                arrayCodigo[i] = tmp.toString();
                tmp = String.valueOf(jXTable1.getValueAt(i, 2));
                arrayRegimen[i] = tmp.toString();

                tmp = String.valueOf(jXTable1.getValueAt(i, 3));
                if (tmp == null || tmp.equals("") || tmp.equals("0.0")) {
                    arrayDeuda[i] = "0.0";
                } else {
                    //pago el impuesto
                    arrayDeuda[i] = tmp.toString();
                }
                tmp = String.valueOf(jXTable1.getValueAt(i, 4));
                if (tmp == null || tmp.equals("") || tmp.equals("0.0")) {
                    arrayPago[i] = "0.0";
                } else {
                    //pago el impuesto
                    arrayPago[i] = tmp.toString();
                }

                tmp = String.valueOf(jXTable1.getValueAt(i, 5));
                if (tmp == null || tmp.equals("") || tmp.equals("0.0")) {
                    arraySaldo[i] = "0.0";
                } else {
                    //pago el impuesto
                    arraySaldo[i] = tmp.toString();
                }
                tmp = String.valueOf(jXTable1.getValueAt(i, 6));
                if (tmp == null || tmp.equals("") || tmp.equals("0.0")) {
                    arrayExoneracion[i] = "0.0";
                } else {
                    //pago el impuesto
                    arrayExoneracion[i] = tmp.toString();
                }

                tmp = String.valueOf(jXTable1.getValueAt(i, 7));
                if (tmp == null || tmp.equals("") || tmp.equals("0.0")) {
                    arrayValor[i] = "0.0";
                } else {
                    //pago el impuesto
                    arrayValor[i] = tmp.toString();
                }
                tmp = String.valueOf(jXTable1.getValueAt(i, 8));
                if (tmp == null || tmp.equals("") || tmp.equals("0.0")) {
                    arrayComentario[i] = "0.0";
                } else {
                    //pago el impuesto
                    arrayComentario[i] = tmp.toString();
                }


            } //for




        } catch (Exception ex) {
            sesion.MostrarMensajeError("Error ", "jMenuItemPagarActionPerformed()\n " + ex.getMessage().toString());
        }
    }

    private void CargarVehiculos() {

        try {
            String Placa = this.jTextFieldPlaca.getText();
            if (Placa == null || Placa.equals("")) {
                JOptionPane.showMessageDialog(this, "Ingrese la placa del vehiculo", "Mensaje", JOptionPane.INFORMATION_MESSAGE);
                return;
            }
            vehiculosBeans.setPlaca(Placa);

            if (vehiculosBeans.ConsultarPorPlaca() == true) {

                if (vehiculosBeans.getPlaca() == null || vehiculosBeans.getPlaca().equals("")) {
                    JOptionPane.showMessageDialog(this, "Este vehiculo no tiene asiganda una placa...", "Mensaje", JOptionPane.INFORMATION_MESSAGE);
                    return;
                }

                jTextFieldId.setText(vehiculosBeans.getId());
                //-----------------------------------
                //----   Verifica el estatus     ----
                //-----------------------------------
                if (vehiculosBeans.getFideicomiso().equals("no")) {
     
                    JOptionPane.showMessageDialog(this, "Este vehiculo no tiene fideicomiso registrado  ", "Mensaje", JOptionPane.INFORMATION_MESSAGE);
                    this.jTextFieldPlaca.setText("");
                    return;
                } 
               
                vehiculosBeans.setTipoId(vehiculosBeans.getTipoId().toLowerCase());
                if (vehiculosBeans.getTipoId().equals("contribuyentes")) {
                    ContribuyentesCargar();
                    jRadioButtonContribuyente.setSelected(true);
                    jRadioButtonComercio.setSelected(false);
                } else {
                    if (vehiculosBeans.getTipoId().equals("comercios")) {
                        ComerciosCargar();
                        jRadioButtonContribuyente.setSelected(false);
                        jRadioButtonComercio.setSelected(true);
                    }
                }

                Actualizar();

            }

        } catch (Exception ex) {
            JOptionPane.showMessageDialog(this, "CargarVehiculos()\nError " + ex.getMessage(), "Error", JOptionPane.ERROR_MESSAGE);
        }


    }

    private void ContribuyentesCargar() {
        try {
            String cedula = this.jTextFieldId.getText();
            if (cedula == null || cedula.equals("")) {
                JOptionPane.showMessageDialog(this, "Ingrese la cedula del contribuyente", "Mensaje", JOptionPane.INFORMATION_MESSAGE);
                return;
            }
            if (sesion.Conectar() == false) {
                JOptionPane.showMessageDialog(this, "No se pudo establecer la conexion", "Mensaje", JOptionPane.INFORMATION_MESSAGE);
                return;
            }

            String sqlquery = "select * from contribuyentes where idmunicipio = ? and cedula = ?";
            PreparedStatement psquery = sesion.con.prepareStatement(sqlquery);
            psquery.setString(1, sesion.getIdmunicipio());
            psquery.setString(2, cedula);
            ResultSet rs = psquery.executeQuery();
            rs.next();
            int x = rs.getRow();
            if (x == 0) {
                JOptionPane.showMessageDialog(this, "No existen registros de contribuyentes con esa cedula", "Mensaje", JOptionPane.INFORMATION_MESSAGE);
                return;
            }
            String activo = rs.getString("activo");
            if (activo.equals("no")) {
                JOptionPane.showMessageDialog(this, "Este registro esta inactivo", "Mensaje", JOptionPane.INFORMATION_MESSAGE);
                return;
            }
            contribuyentesBeans.setCedula(cedula);
            contribuyentesBeans.setContribuyente(rs.getString("contribuyente"));
            contribuyentesBeans.setIdSeguroSocial(rs.getString("idsegurosocial"));
            contribuyentesBeans.setOcupacion(rs.getString("ocupacion"));
            contribuyentesBeans.setNacionalidad(rs.getString("nacionalidad"));
            contribuyentesBeans.setIdMunicipio(rs.getString("idmunicipio"));
            contribuyentesBeans.setIdCorregimiento(rs.getString("idcorregimiento"));
            contribuyentesBeans.setDomicilio(rs.getString("domicilio"));
            contribuyentesBeans.setCasa(rs.getString("casa"));
            contribuyentesBeans.setTelefono(rs.getString("telefono"));
            contribuyentesBeans.setApartadoPostal(rs.getString("apartadopostal"));
            contribuyentesBeans.setEmail(rs.getString("email"));
            contribuyentesBeans.setObservacion(rs.getString("observacion"));
            contribuyentesBeans.setIdMunicipioVive(rs.getString("idmunicipiovive"));
            contribuyentesBeans.setIdCorregimientoVive(rs.getString("idcorregimientovive"));
            contribuyentesBeans.setActivo(rs.getString("activo"));
            contribuyentesBeans.setFoto(rs.getString("foto"));



            if (contribuyentesBeans.getContribuyente() == null || contribuyentesBeans.getContribuyente().equals("")) {
                JOptionPane.showMessageDialog(this, "El contribuyente esta en blanco", "Mensaje", JOptionPane.WARNING_MESSAGE);
                return;
            }

            jTextFieldDueno.setText(contribuyentesBeans.getContribuyente());
            vehiculosBeans.setDueno(contribuyentesBeans.getContribuyente());

        } catch (Exception ex) {
            JOptionPane.showMessageDialog(this, "ContribuyentesCargar()\nError " + ex.getMessage(), "Error", JOptionPane.ERROR_MESSAGE);
        }
    }

    private void ComerciosCargar() {
        try {
            String IdComercio = this.jTextFieldId.getText();
            if (IdComercio == null || IdComercio.equals("")) {
                JOptionPane.showMessageDialog(this, "Ingrese el codigo del comercio", "Mensaje", JOptionPane.INFORMATION_MESSAGE);
                return;
            }
            if (sesion.Conectar() == false) {
                JOptionPane.showMessageDialog(this, "No se pudo establecer la conexion", "Mensaje", JOptionPane.INFORMATION_MESSAGE);
                return;
            }

            String sqlquery = "select comercios.*, contribuyentes.contribuyente from comercios, contribuyentes where comercios.idmunicipio = ? and comercios.idcomercio = ? and comercios.cedula = contribuyentes.cedula";
            PreparedStatement psquery = sesion.con.prepareStatement(sqlquery);
            psquery.setString(1, sesion.getIdmunicipio());
            psquery.setString(2, IdComercio);
            ResultSet rs = psquery.executeQuery();
            rs.next();
            int x = rs.getRow();
            if (x == 0) {
                JOptionPane.showMessageDialog(this, "No existen registros de comercios con ese codigo", "Mensaje", JOptionPane.INFORMATION_MESSAGE);
                return;
            }

            String comercio = rs.getString("comercio");
            String cedula = rs.getString("cedula");
            String contribuyente = rs.getString("contribuyente");
            String Ruc = rs.getString("ruc");
            String Descripcion = rs.getString("descripcion");
            String Direccion = rs.getString("direccion");
            String IdCorregimiento = rs.getString("idcorregimiento");
            String Telefono = rs.getString("telefono");
            String Hipotecado = rs.getString("hipotecado");
            String Bajado = rs.getString("bajado");
            String Traspaso = rs.getString("traspaso");
            String Estatal = rs.getString("estatal");
            String Secuestrado = rs.getString("secuestrado");
            String Activo = rs.getString("activo");

            jTextFieldDueno.setText(comercio);

            if (comercio == null || comercio.equals("")) {
                JOptionPane.showMessageDialog(this, "El comercio esta en blanco", "Mensaje", JOptionPane.WARNING_MESSAGE);
                return;
            }

            comerciosBeans.setIdComercio(IdComercio);
            comerciosBeans.setComercio(comercio);
            comerciosBeans.setCedula(cedula);
            comerciosBeans.setContribuyente(contribuyente);
            comerciosBeans.setRuc(Ruc);
            comerciosBeans.setDescripcion(Descripcion);
            comerciosBeans.setDireccion(Direccion);
            comerciosBeans.setIdCorregimiento(IdCorregimiento);
            comerciosBeans.setTelefono(Telefono);
            comerciosBeans.setHipotecado(Hipotecado);
            comerciosBeans.setBajado(Bajado);
            comerciosBeans.setTraspaso(Traspaso);
            comerciosBeans.setEstatal(Estatal);
            comerciosBeans.setSecuestrado(Secuestrado);
            comerciosBeans.setActivo(Activo);
            vehiculosBeans.setDueno(comerciosBeans.getComercio());
            repaint();

        } catch (Exception ex) {
            JOptionPane.showMessageDialog(this, "ComerciosCargar()\nError " + ex.getMessage(), "Error", JOptionPane.ERROR_MESSAGE);
        }
    }

    private void GuardarLiberacionFideicomiso() {
        try {
            if (sesion.Conectar() == false) {
                JOptionPane.showMessageDialog(this, "No se pudo establecer la conexion", "Mensaje", JOptionPane.INFORMATION_MESSAGE);
                return;
            }
       



            String sql = "update  vehicles set fideicomiso='no' where idmunicipio = ? and idvehiculo = ? and activo='si'";

            PreparedStatement prest1 = sesion.con.prepareStatement(sql);
            prest1.setString(1, sesion.getIdmunicipio()); //placa
            prest1.setInt(2, Integer.parseInt(this.IdVehiculo));

            int count1 = prest1.executeUpdate();


            java.util.Date FechaDateLiberacion = jXDatePickerFechaFinFideicomiso.getDate();
            java.sql.Date FechaFideicomisoLiberacion = new java.sql.Date(FechaDateLiberacion.getTime());
            if (FechaFideicomisoLiberacion == null) {
                JOptionPane.showMessageDialog(this, "Ingrese la fecha de liberacion de  fideicomiso...", "Mensaje", JOptionPane.INFORMATION_MESSAGE);
                jXDatePickerFechaFinFideicomiso.requestFocus();
                return;
            }
            sql = "update vehiclesfideicomiso set idreciboliberacion = ?, fechafideicomisoliberacion=? where idmunicipio=? and idvehiculo =? and activo ='si' ";
            PreparedStatement prest = sesion.con.prepareStatement(sql);
            prest.setInt(1, this.IdRecibo);
            prest.setDate(2, FechaFideicomisoLiberacion);//FECHA
            prest.setString(3, sesion.getIdmunicipio());
            prest.setString(4, this.IdVehiculo); //
           
            int count = prest.executeUpdate();

            sesion.con.close();


        } catch (Exception ex) {
            System.out.println("Error" + ex);
            JOptionPane.showMessageDialog(this, "GuardarLiberacionFideicomiso()\nError " + ex.getMessage(), "Error", JOptionPane.ERROR_MESSAGE);
        }

    }

    private void CargarEntidad() {
        try {
            if (sesion.Conectar() == false) {
                JOptionPane.showMessageDialog(this, "No se pudo establecer la conexion", "Mensaje", JOptionPane.INFORMATION_MESSAGE);
                return;
            }
            String placa = this.jTextFieldPlaca.getText();
            placa = placa.trim();
            String sqlquery = "select vehicleshipoteca.*, entidad.entidad from vehicleshipoteca, entidad  where vehicleshipoteca.idmunicipio='" + sesion.getIdmunicipio() + "' and vehicleshipoteca.placa ='" + placa + "' and entidad.idmunicipio='" + sesion.getIdmunicipio() + "' and vehicleshipoteca.activo='si' and entidad.activo='si' and vehicleshipoteca.identidad = entidad.identidad";
            PreparedStatement psquery = sesion.con.prepareStatement(sqlquery);
            ResultSet rs = psquery.executeQuery();

            int count = 0;
            count = 1;
            while (rs.next()) {
                String entidad = rs.getString("entidad");
                if (entidad != null) {
                    jTextFieldEntidad.setText(entidad);
                }

                Date fecha = rs.getDate("fechahipoteca");
                Format formatter;
                formatter = new SimpleDateFormat("dd/MM/yyyy");
                String s = formatter.format(fecha);
                jFormattedTextFieldFechaFideicomiso.setText(s);


                count++;
            }
            if (count != 0) {
            }


        } catch (Exception ex) {
            JOptionPane.showMessageDialog(this, "CargarEntidad()\nError " + ex.getMessage(), "Error", JOptionPane.ERROR_MESSAGE);
        }
    }

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton jButtonAgregarImpuestos;
    private javax.swing.JButton jButtonBuscarVehiculos;
    private javax.swing.JButton jButtonImprimir;
    private javax.swing.JButton jButtonLimpiar;
    private javax.swing.JButton jButtonNuevoRecibo;
    private javax.swing.JButton jButtonRegresar;
    private javax.swing.JButton jButtonRegresar2;
    private javax.swing.JComboBox jComboBoxExoneracion;
    private javax.swing.JFormattedTextField jFormattedTextFieldFecha;
    private javax.swing.JFormattedTextField jFormattedTextFieldFechaFideicomiso;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel10;
    private javax.swing.JLabel jLabel11;
    private javax.swing.JLabel jLabel12;
    private javax.swing.JLabel jLabel13;
    private javax.swing.JLabel jLabel14;
    private javax.swing.JLabel jLabel16;
    private javax.swing.JLabel jLabel18;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JLabel jLabel5;
    private javax.swing.JLabel jLabel6;
    private javax.swing.JLabel jLabel7;
    private javax.swing.JLabel jLabel8;
    private javax.swing.JLabel jLabel9;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JPanel jPanel5;
    private javax.swing.JPanel jPanelFondo;
    private javax.swing.JRadioButton jRadioButtonComercio;
    private javax.swing.JRadioButton jRadioButtonContribuyente;
    private javax.swing.JScrollPane jScrollPane2;
    private javax.swing.JTextField jTextFieldColor;
    private javax.swing.JTextField jTextFieldDueno;
    private javax.swing.JTextField jTextFieldEntidad;
    private javax.swing.JTextField jTextFieldId;
    private javax.swing.JTextField jTextFieldMarca;
    private javax.swing.JTextField jTextFieldModelo;
    private javax.swing.JTextField jTextFieldPlaca;
    private javax.swing.JTextField jTextFieldRecibo;
    private javax.swing.JTextField jTextFieldTotalExonerado;
    private javax.swing.JTextField jTextFieldTotalPago;
    private org.jdesktop.swingx.JXDatePicker jXDatePickerFechaFinFideicomiso;
    private org.jdesktop.swingx.JXTable jXTable1;
    // End of variables declaration//GEN-END:variables
}
